<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="税源地名称" prop="taxCompanyName" label-width="120px">
        <el-input
          v-model="queryParams.taxCompanyName"
          placeholder="请输入税源地名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务编码" prop="taskNo">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="queryParams['task.invoiceType']">
          <el-option :value="2" label="普票"></el-option>
          <el-option :value="1" label="专票"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票类目" prop="invoiceCatagory">
        <el-input
          v-model="queryParams.invoiceCatagory"
          placeholder="请输入发票类目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleInvoice"
        >批量开票
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="payslipList" @select="handleSelectionChange" @select-all="handleSelectionAllChange">
      <el-table-column :selectable="handleSelectable" type="selection" width="55" align="center"/>
      <el-table-column label="任务编码" align="center" prop="taskNo" min-width="180" />
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="180">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="detailOpen=true;payslipId = row.id">{{ row.task.taskName }}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="税源名称" align="center" prop="taxCompanyName" min-width="180" show-overflow-tooltip/>
      <el-table-column label="打款成功金额" align="center" prop="amount" min-width="100">
        <template slot-scope="{ row }">
          {{ row.successAmount ? row.successAmount : 0 }}元
        </template>
      </el-table-column>

      <el-table-column label="打款成功费率" align="center" prop="amount" min-width="100">
        <template slot-scope="{ row }">
          {{ row.successMerchantAmount ? row.successMerchantAmount : 0 }}元
        </template>
      </el-table-column>


<!--      <el-table-column label="开票类型" align="center" prop="invoiceType" width="100">-->
<!--        <template slot-scope="{ row }">-->
<!--&lt;!&ndash;          <span type="success" v-if="row.task.invoiceType === 1">专票</span>&ndash;&gt;-->
<!--&lt;!&ndash;          <span v-else-if="row.task.invoiceType === 2">普票</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="开票类目" align="center" prop="task.invoiceCatagory" min-width="180"/>

      <el-table-column label="开票状态" align="center" prop="isInvoicing" width="100">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer" type="success" v-if="row.isInvoicing === 0">待开票</el-tag>
          <el-tag style="cursor: pointer" v-else-if="row.isInvoicing === 2">开票中</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="打款时间" align="center" prop="transTime" width="180"></el-table-column>
      <template slot="empty">
        <el-empty :image-size="100"></el-empty>
      </template>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" title="开票" :visible.sync="invoiceOpen" size="65%" append-to-body>
      <el-row :gutter="20">
        <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
          <pane size="28">
            <el-col>
              <div class="head-container">
              </div>
              <div class="head-container">
                <el-tree highlight-current @node-click="handleNodeClick" :default-expanded-keys="defaultExpandedKeys" :data="invoices" ref="tree" node-key="key" :props="{children:'invoices'}">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                       <span v-if="node.level === 1">{{ data.taxCompanyName }}</span>
                       <span v-else>{{ data.invoiceCatagory }}</span>
                    </span>
                </el-tree>
              </div>
            </el-col>
          </pane>
          <pane size="72">
            <el-col>
              <el-descriptions title="申请信息" :column="4">
                <el-descriptions-item label="申请发票类型">{{invoiceInfo.invoiceType===1?'专票':invoiceInfo.invoiceType===2?'普票':''}}</el-descriptions-item>
                <el-descriptions-item :span="3" label="申请类目">{{ invoiceInfo.invoiceCatagory }}
                </el-descriptions-item>
                <el-descriptions-item label="税点/%">{{ invoiceInfo.taxPoint+"%" }}</el-descriptions-item>
                <el-descriptions-item label="税额/元">{{ formattedTotal(invoiceInfo.taxAmount) }}</el-descriptions-item>
                <el-descriptions-item label="不含税金额/元">{{ formattedTotal(invoiceInfo.taskAmount) }}
                </el-descriptions-item>
                <el-descriptions-item label="价税合计/元">{{ formattedTotal(invoiceInfo.invoiceAmount) }}</el-descriptions-item>
                <el-descriptions-item label="扣除额/元">{{ formattedTotal(invoiceInfo.deductionAmount) }}</el-descriptions-item>
              </el-descriptions>
              <el-table :data="invoiceInfo.payslips">
                <el-table-column label="任务编码" align="center" prop="taskNo" min-width="180" />
                <el-table-column label="任务名称" align="center" prop="taskName" min-width="180" />
                <el-table-column label="打款成功金额" align="center" prop="amount" min-width="100">
                  <template slot-scope="{ row }">
                    {{ row.successAmount ? row.successAmount : 0 }}元
                  </template>
                </el-table-column>

                <el-table-column label="打款成功费率" align="center" prop="amount" min-width="100">
                  <template slot-scope="{ row }">
                    {{ row.successMerchantAmount ? row.successMerchantAmount : 0 }}元
                  </template>
                </el-table-column>
              </el-table>
            </el-col>

          </pane>
        </splitpanes>

      </el-row>
      <div class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="subInvoice">立即提交</el-button>
        <el-button :loading="invoiceLoading" @click="invoiceOpen = false">取 消</el-button>
      </div>
    </el-drawer>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="选择增值发票" :visible.sync="open" width="500px" destroy-on-close append-to-body>
      <el-form v-model="invoice">
        <el-select v-model="invoice.invoice">
          <el-option :value="2" label="普票"></el-option>
          <el-option :value="1" label="专票"></el-option>
        </el-select>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import store from '@/store'
import 'splitpanes/dist/splitpanes.css'
import { listTask } from '@/api/system/task'
import { listTaxMarket } from '@/api/tax/taxMarket'
import { listPayslip } from '@/api/transfer/payslip'
import { getInvoiceType } from '@/api/system/InvoiceType'
import { applyForPayslipInvoice } from '@/api/invoice/invoice'
import { Pane, Splitpanes } from 'splitpanes'

export default {
  name: 'applyForInvoice',
  components: { Splitpanes, Pane },
  data() {
    return {
      total: 0,
      open:false,
      loading: false,
      detailOpen: false,
      showSearch: true,
      tslLoading: false,
      invoiceOpen: false,
      taskLoading: false,
      invoiceLoading: false,
      tslOptions: [],
      taskOptions: [],
      selectedRowKeys: [],
      merchantLoading: false,
      merchantOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tslId: null,
        taskId: null,
        params:null,
        taskNo:null,
        isSeparate: 1,
        isInvoicing: 0,
        invoiceType: null,
        taxCompanyName: null,
        invoiceCatagory: null,
      },
      invoice:{
        invoice:"",
      },
      invoices: [],
      invoiceInfo: {
        payslips: []
      },
      payslipId: null,
      payslipList: [],
      defaultExpandedKeys:[],
      organizationType: store.getters.organizationType,
    }
  },
  created() {
    this.getList()
  },
  // mounted() {
  //   this.loading = true
  //   listCooperateTsl({auditStatus: 2, cooperateAuditStatus: 2, limit: 10}).then(response => {
  //     this.loading = false
  //     this.tslOptions = response.rows;
  //     if (this.tslOptions.length > 0){
  //       this.queryParams.taskId = this.tslOptions[0].
  //     }
  //   }).catch(()=>{
  //     this.loading = false
  //   })
  // },
  methods: {
    handleNodeClick(v,d) {
      if (d.level === 2) {
        this.invoiceInfo = v
      }
    },
    getList() {
      this.loading = true
      let search = {
        ...this.queryParams,
        params: {
          // 避免使用In后缀的参数名
          "statusIn": [0,2]
        }
      };
      listPayslip(search).then(response => {
        this.payslipList = response.rows
        this.total = response.total
        this.setSelected()
        this.loading = false
      }).catch(() => {
        this.loading = true
      })
    },

    setSelected() {
      this.payslipList.forEach(item => {
        const isSelected = this.selectedRowKeys.find(row => item.id === row.id)
        item._selected = isSelected
        if (isSelected) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(item, isSelected)
          })
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.selectedRowKeys = [];
      this.invoices = []
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams['task.invoiceType'] = null
      this.queryParams['task.invoiceCatagory'] = null
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleTaskRemote(query) {
      if (query !== '') {
        this.taskLoading = true
        listTask({ taskName: query }).then(response => {
          this.taskOptions = response.rows
          this.taskLoading = false
        }).catch(() => {
          this.taskLoading = false
        })
      }
    },

    handleTslRemote(query) {
      if (query !== '') {
        this.tslLoading = true
        if (this.roleGroup.includes('merchant') || this.roleGroup.includes('agent')) {
          listTaxMarket({ auditStatus: 2, cooperateAuditStatus: 2, name: query }).then(response => {
            this.tslOptions = response.rows
            this.tslLoading = false
          }).catch(() => {
            this.tslLoading = false
          })
        }
      }
    },

    handleSelectionChange(selection, row) {
      const isAdd = selection.some((selectRow) => selectRow.payslipId === row.payslipId)
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }
      this.handleRowChangeAll(row, isAdd)
    },
    handleSelectionAllChange(selection) {
      let isAdd = true
      let changeSelect = selection.slice()

      if (!changeSelect.length) {
        isAdd = false
        changeSelect = this.payslipList.slice()
      }
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }

      for (let i = 0; i < changeSelect.length; i++) {
        const row = changeSelect[i]
        // 检查是否应该终止循环
        this.handleRowChangeAll(row, isAdd)
      }
    },
    handleRowChangeAll(row, isAdd) {
      const index = this.selectedRowKeys.findIndex(
        item => item.payslipId === row.payslipId
      )
      let taskAmount = row.successAmount + row.successMerchantAmount
      if (!taskAmount) {
        taskAmount = 0
      }
      if (index === -1) {
        if (isAdd) {
          // 预检查添加后的数量
          if (this.selectedRowKeys.length >= 1000) {
            this.$refs.table.toggleRowSelection(row, false)
          } else {
            // 查找或创建发票记录
            let invoice = this.invoices.find(item => item.taxOrganizationId === row.taxOrganizationId)

            if (!invoice) {
              invoice = {receiverOrganizationId:row.taxOrganizationId,merchantId:row.merchantId ,organizationType:3, taxOrganizationId: row.taxOrganizationId, taxCompanyName: row.taxCompanyName, invoices: [],key:row.task.taskNo }
              this.invoices.push(invoice)
            }

            // 处理发票分类
            this.prepareCategoryData(row).then(categoryData => {
              this.updateInvoiceCatagorys(invoice, categoryData, row)
            });


            // 添加到选中列表
            this.selectedRowKeys.push({ payslipId: row.payslipId })
          }
        }
      } else {
        if (!isAdd) {
          this.removeInvoiceData(row)
        }
      }
        return false
    },

// 移除发票数据（修复金额计算）
    async removeInvoiceData(row) {
      // 从选中行列表中移除
      const index = this.selectedRowKeys.findIndex(item => item.payslipId === row.payslipId);
      if (index !== -1) {
        this.selectedRowKeys.splice(index, 1);
      }

      // 从发票数据中移除相关信息
      const invoiceIndex = this.invoices.findIndex(item => item.taxOrganizationId === row.taxOrganizationId);

      if (invoiceIndex !== -1) {
        const invoice = this.invoices[invoiceIndex];

        // 优化：先处理所有分类中的工资单移除
        await Promise.all(invoice.invoices.map(async (category) => {
          const payslipIndex = category.payslips.findIndex(payslip => payslip.id === row.id);

          if (payslipIndex !== -1) {
            const categoryData = await this.prepareCategoryData(row);

            // 扣除金额（使用整数运算）
            category.taskAmount = this.toFixedTwoDecimals(
              this.toInteger(category.taskAmount) - categoryData.taskAmount
            );

            category.deductionAmount = category.deductionAmount - categoryData.deductionAmount;

            category.taxAmount = this.toFixedTwoDecimals(
              this.toInteger(category.taxAmount) - categoryData.taxAmountInCents
            );

            category.invoiceAmount = this.toFixedTwoDecimals(
              this.toInteger(category.invoiceAmount) - categoryData.invoiceAmount
            );

            // 移除该工资单
            category.payslips.splice(payslipIndex, 1);
          }
        }));

        // 关键修改：过滤并重新赋值
        invoice.invoices = invoice.invoices.filter(category => category.payslips.length > 0);

        // 如果发票没有分类了，移除整个发票记录
        if (invoice.invoices.length === 0) {
          this.invoices.splice(invoiceIndex, 1);
        }
      }
    },

    // 准备分类数据（分离关注点）
    async prepareCategoryData(row) {
      this.loading = true;
      let taxRate = 0;
      let taxAmount = 0;
      let taskAmount = 0;
      let deductionAmount = 0
      let invoiceAmount = this.toInteger(row.successMerchantAmount) + this.toInteger(row.successAmount);

      try {
        // 等待异步请求完成
        const response = await getInvoiceType(row.taxTerritory.invoiceTypeId);
        taxRate = response.data.invoiceTypeRate;

        if (response.data.invoiceTypeId === "sgake97qwk1uguognnlvlv2z8fl6chi1"){

          let invoiceTypeRate = taxRate / 100

          let divisor = 1 + invoiceTypeRate;

          let serviceAmount = (this.toFixedTwoDecimals(invoiceAmount) - (row.successAmount)).toFixed(2);


          // 计算税额
          taxAmount = (serviceAmount / divisor *  taxRate).toFixed(2)


          // 计算不含税金额 (Y)
          taskAmount = this.toInteger(this.toFixedTwoDecimals(invoiceAmount) - row.successAmount);

          deductionAmount = row.successAmount

        }else{
          // 计算不含税金额和税额（使用整数运算）
          const divisor = 100 + taxRate;

          // 计算不含税金额 (Y) - 使用分作为单位进行计算
          taskAmount = Math.round(invoiceAmount * 100 / divisor);

          // 计算税额 - 使用分作为单位
          taxAmount = invoiceAmount - taskAmount;
        }



      } catch (error) {
        console.error('获取发票类型失败:', error);
        // 处理错误逻辑，例如设置默认值或抛错
      } finally {
        this.loading = false;
      }
      return {
        taskAmount,
        invoiceAmount,
        deductionAmount,
        taxPoint:taxRate,
        taxAmountInCents:taxAmount,
        invoiceType: row.task.invoiceType,
        invoiceCatagory: row.task.invoiceCatagory
      }
    },



// 更新发票分类（分离关注点）
    updateInvoiceCatagorys(invoice, categoryData, row) {
      const { invoiceCatagory, invoiceType, taskAmount, taxAmountInCents, invoiceAmount,taxPoint,deductionAmount } = categoryData
      // 查找或创建分类记录
      let categoryRecord = invoice.invoices.find(
        item => item.invoiceCatagory === invoiceCatagory
      )

      // console.log(taskAmount)

      if (categoryRecord) {
        // 更新现有分类
        categoryRecord.payslips.push({ payslipId: row.payslipId, taskNo: row.taskNo,taskName:row.task.taskName,successAmount:row.successAmount,transTime:row.transTime,successMerchantAmount:row.successMerchantAmount, })
        categoryRecord.taxAmount =  this.toFixedTwoDecimals(
          this.toInteger(categoryRecord.taxAmount) + parseFloat(taxAmountInCents)
        )
        categoryRecord.taskAmount = this.toFixedTwoDecimals(
          this.toInteger(categoryRecord.taskAmount) + parseFloat(taskAmount)
        )
        categoryRecord.deductionAmount = categoryRecord.deductionAmount + deductionAmount
        categoryRecord.invoiceAmount = this.toFixedTwoDecimals(
          this.toInteger(categoryRecord.invoiceAmount) + invoiceAmount
        )
      } else {
        // 创建新分类
        invoice.invoices.push({
          key:row.taxOrganizationId+invoiceCatagory,
          invoiceType:invoiceType,
          taxPoint:taxPoint,
          invoiceCatagory:invoiceCatagory,
          deductionAmount:deductionAmount,
          invoiceAmount: this.toFixedTwoDecimals(invoiceAmount),
          taskAmount: this.toFixedTwoDecimals(taskAmount),
          taxAmount: this.toFixedTwoDecimals(taxAmountInCents),
          payslips: [{ payslipId: row.payslipId, taskNo: row.taskNo,taskName:row.task.taskName,successAmount:row.successAmount,transTime:row.transTime,successMerchantAmount:row.successMerchantAmount, }]
        })
      }
    },

    handleInvoice() {
      if (this.selectedRowKeys.length === 0 || this.invoices.length === 0) {
        this.$message.warning('暂无数据')
        return
      }
      this.handleNodeClick( this.invoices[0].invoices[0],{level:2})
      this.invoiceOpen = true
      this.$nextTick(() => {
        this.defaultExpandedKeys = [this.invoices[0]]
        this.$refs.tree.setCurrentNode(this.invoices[0].invoices[0])
      })

    },

    // 选择条件函数
    handleSelectable(row) {
      // 如果已达到选择上限，且当前行未被选中，则禁用选择
      if (this.selectedRowKeys.length >= 1000 && !!this.selectedRowKeys.findIndex(item => item.id === row.id)) {
        return false
      }

      if (row.isInvoicing !== 0) {
        return false
      }

      // 其他条件禁用（示例中的disabled字段）
      return !row.disabled
    },

    subInvoice() {
      this.$modal.confirm('确定要提交这些任务吗？').then(() => {
        this.invoiceLoading = true
        applyForPayslipInvoice(this.invoices).then(res => {
          this.selectedRowKeys = []
          this.invoices=[]
          this.invoiceLoading = false
          this.invoiceOpen = false
          this.getList()
        }).catch(() => {
          this.invoiceLoading = false
        })
      })

    },
    totalAmount(amount) {
      const tax = this.safeAdd(0, amount * 0.06) // 确保 tax 至少为 0

      return this.formattedTotal(this.safeAdd(amount, tax))
    },
    safeAdd(a, b) {
      return (Math.round(a * 100) + Math.round(b * 100)) / 100
    },

    formattedTotal(amount) {
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    // 辅助方法：转换为整数（处理金额）
    toInteger(value) {
      if (typeof value === 'number') return Math.round(value * 100)
      if (typeof value === 'string') return Math.round(parseFloat(value) * 100)
      return 0
    },

    // 辅助方法：转换为两位小数的字符串
    toFixedTwoDecimals(amountInCents) {
      return (amountInCents / 100).toFixed(2)
    }
  }
}
</script>

<style scoped lang="scss">
.dialog-footer{
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  height: 55px;
  padding: 10px 20px;
  position: absolute;
  justify-content: flex-end;
  background-color: #ffffff;
  box-shadow: 0 0 4px rgba(0, 21, 41, 0.35);
}
</style>
